# -*- coding: utf-8 -*-
import scrapy
import re
from urllib import parse
from scrapy import Request
from scrapy import Selector
import json


class BattleSpider(scrapy.Spider):
    name = 'battle'
    allowed_domains = ['jp.op.gg']
    start_urls = ['https://jp.op.gg/summoner/userName=luluuu/']

    def parse(self, response):
        summonerId = response.xpath('//div[@class="GameListContainer"]/@data-summoner-id').extract_first("")
        lastInfo = response.xpath('//div[@class="GameListContainer"]/@data-last-info').extract_first("")
        # gameTime = response.xpath('//div[@class="GameItem Win  "]/@data-game-time').extract()
        post_nodes = response.xpath('//div[@class="GameItemList"]//div[@class="GameItemWrap"]')
        # text = response.text
        # for post_node in post_nodes:
        #     gameId = post_node.css('.GameItem::attr(data-game-id)').extract_first("")
        #     gameTime = post_node.css('.GameItem::attr(data-game-time)').extract_first("")
        #     yield Request(url=parse.urljoin(response.url, "/summoner/matches/ajax/detail/gameId={}&summonerId={}&gameTime={}".format(gameId, summonerId, gameTime)), callback=self.parse_detail)

        if lastInfo != '':
            yield Request(url=parse.urljoin(response.url,
                                            "/summoner/matches/ajax/averageAndList/startInfo={}&summonerId={}".format(
                                                lastInfo, summonerId)),  meta={"summoner_id":summonerId}, callback=self.parse_next)
        pass


    def parse_next(self, response):
        if response.status == 200:
            summoner_id = response.meta.get("summoner_id", "")
            j_data = json.loads(response.text)
            last_info = j_data['lastInfo']
            html = j_data['html']
            post = Selector(text=html)
            post_nodes = post.xpath('//div[@class="GameItemList"]//div[@class="GameItemWrap"]')
            for post_node in post_nodes:
                gameId = post_node.css('.GameItem::attr(data-game-id)').extract_first("")
                gameTime = post_node.css('.GameItem::attr(data-game-time)').extract_first("")
                yield Request(url=parse.urljoin(response.url,
                                                "/summoner/matches/ajax/detail/gameId={}&summonerId={}&gameTime={}".format(
                                                    gameId, summoner_id, gameTime)), callback=self.parse_detail)
            yield Request(url=parse.urljoin(response.url,
                                            "/summoner/matches/ajax/averageAndList/startInfo={}&summonerId={}".format(
                                                last_info, summoner_id)),  meta={"summoner_id":summoner_id}, callback=self.parse_next)

        pass

    def parse_detail(self, response):
        win_summary = response.css('.Summary .Result-WIN .ObjectScore::text').extract()
        win_summary_num = []
        for win_str in win_summary:
            match_re = re.sub(r'\s+', '', win_str)
            if match_re != '':
                win_summary_num.append(match_re)
        # 胜
        # 男爵
        win_baron = win_summary_num[0]
        # 小龙
        win_dragon = win_summary_num[1]
        # 防御塔
        win_defense = win_summary_num[2]
        lost_summary = response.css('.Summary .Result-LOSE .ObjectScore::text').extract()
        lost_summary_num = []
        for lost_str in lost_summary:
            match_re = re.sub(r'\s+', '', lost_str)
            if match_re != '':
                lost_summary_num.append(match_re)
        # 败
        lost_baron = lost_summary_num[0]
        lost_dragon = lost_summary_num[1]
        lost_defense = lost_summary_num[2]



        # post = Selector(text=response.text)
        win_list = response.css('.Result-WIN .Content .Row')
        # 胜利队伍列表
        win_hero_list = []
        for item in win_list:
            hero = dict()
            # 使用英雄名字
            hero_name = item.css('.ChampionImage a .Image::text').extract_first("")
            hero['hero_name'] = hero_name
            # 当局等级
            hero_level = item.css('.ChampionImage a .Level::text').extract_first("")
            hero['hero_level'] = hero_level
            # 召唤师技能1 2
            # TODO list数量判定分别拿出技能
            skill = item.css('.SummonerSpell img::attr(src)').extract()
            hero['skill'] = skill
            # 天赋1 2
            # TODO list数量判定分别拿出技能
            rune = item.css('.Rune img::attr(src)').extract()
            hero['rune'] = rune
            # 召唤师昵称
            summoner_name = item.css('.SummonerName a::text').extract_first("")
            hero['summoner_name'] = summoner_name
            # KDA值
            kda = item.css('.KDA span::text').extract_first("")
            hero['kda'] = kda
            # kill
            kill = item.css('.KDA .KDA .Kill::text').extract_first("")
            hero['kill'] = kill
            # death
            death = item.css('.KDA .KDA .Death::text').extract_first("")
            hero['death'] = death
            # assist
            assist = item.css('.KDA .KDA .Assist::text').extract_first("")
            hero['assist'] = assist
            # 参团率
            ck_rate = item.css('.KDA .KDA .CKRate::text').extract_first("")
            hero['ck_rate'] = ck_rate
            # 伤害
            damage = item.css('.Damage .ChampionDamage::text').extract_first("")
            hero['damage'] = damage
            # 真眼数
            control_ward = item.css('.Ward .Buy span::text').extract_first("")
            hero['control_ward'] = control_ward
            # 插眼数
            ward = item.css('.Ward .Stats span::text').extract()
            hero['ward'] = ward
            # 清眼数

            # 补刀数
            cs = item.css('.CS .CS::text').extract_first("")
            hero['cs'] = cs
            # 每分钟补刀数
            cs_per_minute = item.css('.CS .CSPerMinute::text').extract_first("")
            hero['cs_per_minute'] = cs_per_minute
            # 道具图标list
            item_list = item.css('.Items .Item img::attr(src)').extract()
            hero['item_list'] = item_list
            # 道具名称
            item_name_list = item.css('.Items .Item img::attr(alt)').extract()
            hero['item_name_list'] = item_name_list
            win_hero_list.append(hero)

        lose_list = response.css('.Result-LOSE .Content .Row')
        # 失败队伍列表
        lose_hero_list = []
        for item in lose_list:
            hero = dict()
            # 使用英雄名字
            hero_name = item.css('.ChampionImage a .Image::text').extract_first("")
            hero['hero_name'] = hero_name
            # 当局等级
            hero_level = item.css('.ChampionImage a .Level::text').extract_first("")
            hero['hero_level'] = hero_level
            # 召唤师技能1 2
            skill = item.css('.SummonerSpell img::attr(src)').extract()
            hero['skill'] = skill
            # 天赋
            rune = item.css('.Rune img::attr(src)').extract()
            hero['rune'] = rune
            # 召唤师昵称
            summoner_name = item.css('.SummonerName a::text').extract_first("")
            hero['summoner_name'] = summoner_name
            # KDA值
            kda = item.css('.KDA span::text').extract_first("")
            hero['kda'] = kda
            # kill
            kill = item.css('.KDA .KDA .Kill::text').extract_first("")
            hero['kill'] = kill
            # death
            death = item.css('.KDA .KDA .Death::text').extract_first("")
            hero['death'] = death
            # assist
            assist = item.css('.KDA .KDA .Assist::text').extract_first("")
            hero['assist'] = assist
            # 参团率
            ck_rate = item.css('.KDA .KDA .CKRate::text').extract_first("")
            hero['ck_rate'] = ck_rate
            # 伤害
            damage = item.css('.Damage .ChampionDamage::text').extract_first("")
            hero['damage'] = damage
            # 真眼数
            control_ward = item.css('.Ward .Buy span::text').extract_first("")
            hero['control_ward'] = control_ward
            # 插眼数
            ward = item.css('.Ward .Stats span::text').extract()
            hero['ward'] = ward
            # 清眼数

            # 补刀数
            cs = item.css('.CS .CS::text').extract_first("")
            hero['cs'] = cs
            # 每分钟补刀数
            cs_per_minute = item.css('.CS .CSPerMinute::text').extract_first("")
            hero['cs_per_minute'] = cs_per_minute
            # 道具图标list
            item_list = item.css('.Items .Item img::attr(src)').extract()
            hero['item_list'] = item_list
            # 道具名称
            item_name_list = item.css('.Items .Item img::attr(alt)').extract()
            hero['item_name_list'] = item_name_list
            lose_hero_list.append(hero)

        # text = response.text
        # print(text)
        pass

